<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Api extends Controller
{
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        apiReturn(1, '获取数据成功', $openid);
    }

    public function openidToUserid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_id = Db::name('user')->where(['openid' => $openid])->value('id');

        if ($user_id) {
            apiReturn(1, '登录成功', $user_id);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }


    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $username = $input['username'];

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像信息');
        if (empty($username)) apiReturn(2, '请填写昵称');

        $data = [
            'openid' => $openid,
            'avatar' => $avatar,
            'username' => $username,
            'create_time' => time()
        ];

        $count = Db::name('user')->where(['openid' => $openid])->count();
        if ($count) {
            $user_id = Db::name('user')->where(['openid' => $openid])->value('id');
        } else {
            $user_id = Db::name('user')->insertGetId($data);
        }

        apiReturn(1, '登录成功', $user_id);
    }

    public function updateTime()
    {
        $list = Db::name('user')->where(['create_time' => 0, 'update_time' => ['gt', 0]])->select();
        if ($list) {
            foreach ($list as &$v) {
                Db::name('user')->where(['id' => $v['id']])->update(['create_time' => $v['update_time']]);
            }
        }
    }

    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $banner_list = Db::name('banner')->field('id,img,type,to_id')->order('id desc')->select();

        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 获取用户是否认证
     * */
    public function getUserProve()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('user')->field('student_prove_id,company_prove_id')->where(['id' => $user_id])->find();

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 学生认证
     * */
    public function studentProve()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;// id存在则为修改认证信息
        $user_id = $input['user_id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $xsz_img = $input['xsz_img'];
        $imgs = $input['imgs'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入联系电话');
        if (!preg_match("/^1[3-9]\d{9}$/", $mobile)) apiReturn(2, '手机号码有误，请重新输入');
        if (empty($xsz_img)) apiReturn(2, '请上传学生证');
        if (empty($imgs)) apiReturn(2, '请上传身份证或户口簿照片');
        $imgs_arr = doImgs($imgs);
        if (count($imgs_arr) < 2) apiReturn(2, '证件照片必须上传2张');

        $count_where['mobile'] = $mobile;
        if ($id) $count_where['id'] = ['neq', $id];
        $count = Db::name('student_prove')->where($count_where)->count();
        if ($count) apiReturn(2, '该手机号已被使用');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if ($user_info) {
            Db::startTrans();
            try {
                $data = [
                    'username' => $username,
                    'mobile' => $mobile,
                    'xsz_img' => $xsz_img,
                    'imgs' => $imgs
                ];

                /*$idCard_check_res = true;
                for ($i = 0; $i < count($imgs_arr); $i++){
                    if(!$this->checkCert($imgs_arr[$i]['path'])){
                        $idCard_check_res = false;
                        break;
                    }
                }
                if($idCard_check_res){
                    $house_check_res = true;
                    for ($i = 0; $i < count($imgs_arr); $i++){
                        if(!$this->checkCert($imgs_arr[$i]['path'], 2)){
                            $house_check_res = false;
                            break;
                        }
                    }
                }
                if(!$idCard_check_res && !$house_check_res) apiReturn(2,'证件照片有误，请重新上传');*/

                if ($student_prove_id = $id) {
                    // 修改学生认证
                    $data['update_time'] = time();
                    Db::name('student_prove')->where(['id' => $student_prove_id])->update($data);
                } else {
                    // 新增学生认证
                    $data['create_time'] = time();
                    $student_prove_id = Db::name('student_prove')->insertGetId($data);
                }

                $data = [
                    'student_prove_id' => $student_prove_id,
                    'type' => 1,
                    'mobile' => $mobile,
                    'update_time' => time()
                ];
                Db::name('user')->where(['id' => $user_id])->update($data);

                Db::commit();
                apiReturn(1, '提交成功', $student_prove_id);
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '提交失败');
            }
        } else {
            apiReturn(2, '用户不存在');
        }
    }

    /**
     * 企业认证
     * */
    public function companyProve()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $user_id = $input['user_id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $type = $input['type'] ? : 1;
        $img = $input['img'];
        $company_name = $input['company_name'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($username)) apiReturn(2, '请输入负责人姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (!preg_match("/^1[3-9]\d{9}$/", $mobile)) apiReturn(2, '手机号码有误，请重新输入');
        if (empty($img)) apiReturn(2, '请上传相关证件');
        if (empty($company_name)) apiReturn(2, '请输入企业名称');

        $count_where['mobile'] = $mobile;
        if ($id) $count_where['id'] = ['neq', $id];
        $count = Db::name('company_prove')->where($count_where)->count();
        if ($count) apiReturn(2, '该手机号已被使用');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if ($user_info) {
            Db::startTrans();
            try {
                $data = [
                    'username' => $username,
                    'mobile' => $mobile,
                    'type' => $type,
                    'img' => $img,
                    'company_name' => $company_name
                ];

                if ($company_prove_id = $user_info['company_prove_id']) {
                    // 修改企业认证
                    $data['update_time'] = time();
                    Db::name('company_prove')->where(['id' => $company_prove_id])->update($data);
                } else {
                    // 新增企业认证
                    $data['create_time'] = time();
                    $company_prove_id = Db::name('company_prove')->insertGetId($data);
                }

                $data = [
                    'company_prove_id' => $company_prove_id,
                    'type' => 2,
                    'mobile' => $mobile,
                    'update_time' => time()
                ];
                Db::name('user')->where(['id' => $user_id])->update($data);

                Db::commit();
                apiReturn(1, '提交成功', $company_prove_id);
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '提交失败');
            }
        } else {
            apiReturn(2, '用户不存在');
        }
    }

    /**
     * 项目体验列表
     * */
    public function projectList()
    {
        $input = Request()->param();

        $tab = $input['tab'] ? : 0;// 0:全部，1：最新（去除已结束的数据）
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['is_online'] = 1;
        if ($tab == 1) {
            $where['status'] = ['neq', 3];
        } else {
            $where['status'] = ['IN', [2, 3]];
        }

        $list = Db::name('project')->field('id,user_id,name,end_time')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $company_info = getCompanyInfo($v['user_id']);
                $v['company_name'] = $company_info['company_name'] ? : '';

                $post_list = Db::name('post')->field('id,name,time')->where(['project_id' => $v['id']])->order('create_time desc')->select();
                $v['post_list'] = $post_list ? : [];

                $v['is_end'] = $v['status'] == 3 || $v['end_time'] <= time() ? 1 : 0;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 项目详情
     * */
    public function projectDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'] ? : 0;

        if (empty($id)) apiReturn(2, '项目ID缺失');

        if ($user_id) {
            $user_info = Db::name('user')->where(['id' => $user_id])->find();
            if (empty($user_info)) apiReturn(2, '您的用户信息不存在或已被禁用');
        }

        $info = Db::name('project')->field('id,user_id,name,head_name,head_mobile,applicable_objects,address,content,file_ids,status')->where(['id' => $id])->find();
        if ($info) {
            // 企业信息
            $company_info = getCompanyInfo($info['user_id']);
            $info['company_info'] = $company_info;

            // 岗位列表
            $post_list = Db::name('post')->field('id,name,max_count,time,counsellor_name,counsellor_unit')->where(['project_id' => $info['id']])->order('create_time desc')->select();
            if ($post_list && $user_id) {
                foreach ($post_list as &$v) {
                    $is_join = Db::name('post_join')->where(['user_id' => $user_id, 'post_id' => $v['id'], 'status' => ['neq', -1]])->count();
                    $v['is_join'] = (bool)$is_join;

                    if ($user_info['student_prove_id']) {
                        // 学生端：join_count = 报名成功的人数
                        $success_post_join_count = Db::name('post_join')->where(['post_id' => $v['id'], 'status' => 2])->count();
                        $v['join_count'] = $success_post_join_count;
                    } elseif ($user_info['company_prove_id']) {
                        // 企业端：join_count = 待审核 + 已审核
                        $join_count = Db::name('post_join')->where(['post_id' => $v['id'], 'status' => ['IN', [1, 2]]])->count();
                        $v['join_count'] = $join_count;
                    }

                    $v['time'] = $v['time'] ? : '';
                }
            }
            $info['post_list'] = $post_list ? : [];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '项目不存在或已删除');
        }
    }

    /**
     * 岗位报名界面信息回显
     * */
    public function postJoinInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $project_id = $input['project_id'];
        $post_id = $input['post_id'];

        if (empty($project_id)) apiReturn(2, '项目ID缺失');
        if (empty($post_id)) apiReturn(2, '岗位ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $project_info = Db::name('project')->field('id,user_id,name,applicable_objects,head_name,head_mobile')->where(['id' => $project_id])->find();
        if (empty($project_info)) apiReturn(2, '项目不存在或已删除');

        $company_info = getCompanyInfo($project_info['user_id']);
        if (empty($company_info)) apiReturn(2, '承办单位不存在或已删除');

        $post_info = Db::name('post')->field('id,name,max_count,time,counsellor_name,counsellor_unit')->where(['id' => $post_id])->find();
        if (empty($post_info)) apiReturn(2, '岗位不存在或已删除');
        $join_count = Db::name('post_join')->where(['post_id' => $post_id])->count();
        $post_info['join_count'] = $join_count ? : 0;

        $student_prove_info = Db::name('student_prove s')->join('pr_user u', 'u.student_prove_id = s.id')
            ->field('u.id,s.username,s.xsz_img,s.imgs')
            ->where(['u.id' => $user_id])
            ->find();
        if (empty($student_prove_info)) apiReturn(2, '认证信息不存在或已删除');

        $student_prove_info['xsz_img'] = getPicture($student_prove_info['xsz_img']);
        $student_prove_info['imgs'] = doImgs($student_prove_info['imgs']);

        $data = [
            'project_info' => $project_info,
            'company_info' => $company_info,
            'post_info' => $post_info,
            'student_prove_info' => $student_prove_info
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 报名岗位
     * */
    public function postSignUp()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $project_id = $input['project_id'];
        $post_id = $input['post_id'];

        if (empty($project_id)) apiReturn(2, '项目ID缺失');
        if (empty($post_id)) apiReturn(2, '岗位ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $release_user_id = Db::name('project')->where(['id' => $project_id])->value('user_id');
        if (empty($release_user_id)) apiReturn(2, '项目发起人缺失');

        $count = Db::name('post_join')->where(['user_id' => $user_id, 'post_id' => $post_id, 'status' => ['neq', -1]])->count();
        if ($count) apiReturn(2, '您已报名该岗位，请勿重复报名');

        $post_info = Db::name('post')->where(['id' => $post_id])->find();
        if (empty($post_info)) apiReturn(2, '岗位不存在');

        $success_post_join_count = Db::name('post_join')->where(['post_id' => $post_id, 'status' => 2])->count();
        if ($success_post_join_count >= $post_info['max_count']) apiReturn(2, '当前岗位已达报名上限');

        Db::startTrans();
        try {
            $data = [
                'user_id' => $user_id,
                'release_user_id' => $release_user_id,
                'project_id' => $project_id,
                'post_id' => $post_id,
                'create_time' => time()
            ];
            $post_join_id = Db::name('post_join')->insertGetId($data);

            $post_name = Db::name('post')->where(['id' => $post_id])->value('name');
            $msg_data = [
                'user_id' => $release_user_id,
                'title' => '岗位报名处理',
                'content' => '针对' . getProjectName($project_id) . '项目的' . $post_name . '岗位，有一条报名申请，请及时处理',
                'type' => 4,
                'to_id' => $post_join_id,
                'create_time' => time()
            ];
            Db::name('msg')->insert($msg_data);

            Db::commit();
            apiReturn(1, '提交成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '报名失败');
        }
    }

    /**
     * 我的报名列表
     * */
    public function userPostList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['pj.user_id'] = $user_id;
        if ($status) $where['pj.status'] = $status;

        $list = Db::name('post_join pj')
            ->join('pr_project j', 'pj.project_id = j.id', 'LEFT')
            ->join('pr_post p', 'pj.post_id = p.id', 'LEFT')
            ->field('pj.id,pj.project_id,pj.post_id,pj.user_id,pj.status,pj.refuse_reason,j.name project_name,p.name post_name,j.head_name,j.head_mobile,p.time,p.counsellor_name,p.counsellor_unit')
            ->where($where)
            ->order('pj.create_time desc')
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                switch ($v['status']) {
                    case 1:
                        $status_desc = '待审核';
                        break;
                    case 2:
                        $status_desc = '已审核';
                        break;
                    case -1:
                        $status_desc = '未通过';
                        break;
                    default:
                        $status_desc = '';
                        break;
                }
                $v['status_desc'] = $status_desc;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 项目申请页面数据回显
     * */
    public function applyProjectPage()
    {
        $input = Request()->param();

        $company_prove_id = $input['company_prove_id'];

        if (empty($company_prove_id)) apiReturn(2, '企业认证ID缺失');

        $company_info = Db::name('company_prove')->field('type,company_name')->where(['id' => $company_prove_id])->find();
        if ($company_info) {
            // 1：民企，2：机关单位，3：社会组织
            switch ($company_info['type']) {
                case 1:
                    $type_desc = '民企';
                    break;
                case 2:
                    $type_desc = '机关单位';
                    break;
                case 3:
                    $type_desc = '社会组织';
                    break;
            }
            $company_info['type_desc'] = $type_desc;

            $project_file = Db::name('project_file')->where(['type' => 1])->order('type asc')->select();
            if ($project_file) {
                foreach ($project_file as &$v) {
                    $v['all_name'] = $v['name'];
                    $v['name'] = removeFileExtension($v['name']);
                    $v['file_url'] = getHost() . getFile($v['file_id'])['path'];
                }
            }

            $data = [
                'company_info' => $company_info,
                'project_file' => $project_file
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '未进行企业认证');
        }
    }

    /**
     * 项目申请提交
     * */
    public function doProject()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $user_id = $input['user_id'];
        $name = $input['name'];
        $applicable_objects = $input['applicable_objects'];
        $head_name = $input['head_name'];
        $head_mobile = $input['head_mobile'];
        $content = $input['content'];
        $file_ids = $input['file_ids'];
        $post_data = $input['post_data'];
        $end_time = $input['end_time'];
        $address = $input['address'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($name)) apiReturn(2, '请输入体验项目名称');
        if (empty($content)) apiReturn(2, '请输入简介');
        if (empty($applicable_objects)) apiReturn(2, '请输入适用对象');
        if (empty($head_name)) apiReturn(2, '请输入负责人姓名');
        if (empty($head_mobile)) apiReturn(2, '请输入负责人电话');
        if (!preg_match("/^1[3-9]\d{9}$/", $head_mobile)) apiReturn(2, '负责人电话有误，请重新输入');
        if (empty($file_ids)) apiReturn(2, '请上传申报资料');
        if (empty($post_data)) apiReturn(2, '请完善岗位信息');
        if (empty($end_time)) apiReturn(2, '请选择结束时间');
        if (empty($address)) apiReturn(2, '请输入地址');

        $post_db_data = [];
        if ($post_data) {
            foreach ($post_data as &$v) {
                if (!$v['name'] || !$v['max_count'] || !$v['time'] || !$v['counsellor_name'] || !$v['counsellor_unit']) apiReturn(2, '请完善岗位信息');

                $post_db_data[] = [
                    'id' => $v['id'] ? : 0,
                    'name' => $v['name'],
                    'max_count' => $v['max_count'],
                    'time' => $v['time'],
                    'counsellor_name' => $v['counsellor_name'],
                    'counsellor_unit' => $v['counsellor_unit'],
                ];
            }
        } else {
            apiReturn(2, '岗位信息错误');
        }

        $data = [
            'user_id' => $user_id,
            'name' => $name,
            'applicable_objects' => $applicable_objects,
            'head_name' => $head_name,
            'head_mobile' => $head_mobile,
            'content' => $content,
            'file_ids' => $file_ids,
            'end_time' => strtotime($end_time) + 24 * 3600 - 1,
            'address' => $address,
        ];


        $time = time();

        Db::startTrans();
        try {
            if ($id) {
                // 编辑
                $data['status'] = 1;
                $data['update_time'] = $time;

                Db::name('project')->where(['id' => $id])->update($data);

                if ($post_db_data) {
                    foreach ($post_db_data as &$v) {
                        if ($v['id']) {
                            // 修改
                            $update_data = [
                                'name' => $v['name'],
                                'max_count' => $v['max_count'],
                                'time' => $v['time'],
                                'counsellor_name' => $v['counsellor_name'],
                                'counsellor_unit' => $v['counsellor_unit'],
                                'update_time' => $time
                            ];
                            Db::name('post')->where(['id' => $v['id']])->update($update_data);
                        } else {
                            // 新增
                            $insert_data = [
                                'name' => $v['name'],
                                'project_id' => $id,
                                'max_count' => $v['max_count'],
                                'time' => $v['time'],
                                'counsellor_name' => $v['counsellor_name'],
                                'counsellor_unit' => $v['counsellor_unit'],
                                'create_time' => $time
                            ];
                            Db::name('post')->insert($insert_data);
                        }
                    }
                }
            } else {
                // 新增
                $data['create_time'] = $time;

                $project_id = Db::name('project')->insertGetId($data);

                if ($post_db_data) {
                    $post_db_data = array_map(function ($item) use ($project_id, $time) {
                        $item['project_id'] = $project_id;
                        $item['create_time'] = $time;
                        return $item;
                    }, $post_db_data);

                    Db::name('post')->insertAll($post_db_data);
                }
            }

            Db::commit();
            apiReturn(1, '提交成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '提交失败' . $e->getMessage());
        }


    }

    /**
     * 项目管理
     * */
    public function userProjectList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        if ($status) $where['status'] = $status;

        $list = Db::name('project')->field('id,name,head_name,head_mobile,status,refuse_reason')->where($where)->order('create_time desc')->page($page, $pagesize)->select();

        if ($list) {
            foreach ($list as &$v) {
                $post_list = Db::name('post')->field('id,name,time,counsellor_name,counsellor_unit')->where(['project_id' => $v['id']])->order('create_time desc')->select();
                $v['post_list'] = $post_list ? : [];

                // 已报名人数
                $join_count = Db::name('post_join')->where(['project_id' => $v['id']])->count();
                $v['join_count'] = $join_count ? : 0;

                switch ($v['status']) {
                    case 1:
                        $status_desc = '待审核';
                        break;
                    case 2:
                        $status_desc = '已审核';
                        break;
                    case 3:
                        $status_desc = '已结束';
                        break;
                    case -1:
                        $status_desc = '未通过';
                        break;
                    default:
                        $status_desc = '';
                        break;
                }
                $v['status_desc'] = $status_desc;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 报名审核列表
     * */
    public function examinePostJoinList()
    {
        $input = Request()->param();

        $project_id = $input['project_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($project_id)) apiReturn(2, '项目ID缺失');

        $where['pj.project_id'] = $project_id;
        if ($status) $where['pj.status'] = $status;

        $list = Db::name('post_join pj')
            ->join('pr_project j', 'pj.project_id = j.id', 'LEFT')
            ->join('pr_post p', 'pj.post_id = p.id', 'LEFT')
            ->field('pj.id,j.name project_name,p.name post_name,pj.status,pj.user_id')
            ->where($where)
            ->order('pj.create_time desc')
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $user_info = Db::name('user u')->join('pr_student_prove p', 'u.student_prove_id = p.id', 'left')
                    ->field('p.username,p.mobile')
                    ->where(['u.id' => $v['user_id']])
                    ->find();

                $v['username'] = $user_info['username'];
                $v['mobile'] = $user_info['mobile'];

                switch ($v['status']) {
                    case 1:
                        $status_desc = '待审核';
                        break;
                    case 2:
                        $status_desc = '已审核';
                        break;
                    case -1:
                        $status_desc = '未通过';
                        break;
                    default:
                        $status_desc = '';
                        break;
                }
                $v['status_desc'] = $status_desc;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 报名审核详情
     * */
    public function examinePostJoinDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, 'ID缺失');

        $info = Db::name('post_join')->field('id,user_id,project_id,post_id,status')->where(['id' => $id])->find();
        if ($info) {
            // 学生信息
            $student_prove_info = Db::name('student_prove s')->join('pr_user u', 'u.student_prove_id = s.id')
                ->field('u.id,s.username,s.mobile,s.xsz_img,s.imgs')
                ->where(['u.id' => $info['user_id']])
                ->find();

            if (empty($student_prove_info)) apiReturn(2, '用户不存在或已删除');
            $student_prove_info['xsz_img'] = getPicture($student_prove_info['xsz_img']);
            $student_prove_info['imgs'] = doImgs($student_prove_info['imgs']);
            $info['student_prove_info'] = $student_prove_info;

            // 项目名称
            $info['project_name'] = getProjectName($info['project_id']);

            $post_info = Db::name('post')->where(['id' => $info['post_id']])->find();
            $info['post_name'] = $post_info['name'];
            $info['time'] = $post_info['time'];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '数据不存在');
        }
    }

    /**
     * 审核学生报名
     * */
    public function doStudentPost()
    {
        $input = Request()->param();

        $id = $input['id'];// 申请记录id
        $status = $input['status'];
        $refuse_reason = $input['refuse_reason'];

        if (empty($id)) apiReturn(2, 'ID缺失');
        if (empty($status)) apiReturn(2, '审核状态缺失');
        if ($status == -1 && empty($refuse_reason)) apiReturn(2, '请输入拒绝原因');

        $info = Db::name('post_join')->where(['id' => $id])->find();
        if ($info) {
            // 岗位信息
            $post_info = Db::name('post')->where(['id' => $info['post_id']])->find();
            if (empty($post_info)) apiReturn(2, '岗位不存在');

            $success_post_join_count = Db::name('post_join')->where(['post_id' => $info['post_id'], 'status' => 2])->count();
            if ($success_post_join_count >= $post_info['max_count']) apiReturn(2, '当前岗位已达报名上限');

            Db::startTrans();
            try {
                $time = time();
                $join_post_data = [
                    'status' => $status,
                    'refuse_reason' => $refuse_reason,
                    'update_time' => $time
                ];
                Db::name('post_join')->where(['id' => $id])->update($join_post_data);

                $project_name = getProjectName($info['project_id']);
                $post_name = getPostName($info['post_id']);
                $msg_data = [
                    'user_id' => $info['user_id'],
                    'title' => '岗位报名',
                    'content' => '针对' . $project_name . '项目的' . $post_name . '岗位的报名审核' . ($status == -1 ? ('不通过，原因：' . $refuse_reason) : '通过'),
                    'type' => 1,
                    'to_id' => $id,
                    'create_time' => $time
                ];
                Db::name('msg')->insert($msg_data);

                Db::commit();
                apiReturn(1, '提交成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '提交失败');
            }
        } else {
            apiReturn(2, '审核记录不存在或已删除');
        }

    }

    function sendRequest($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }

        curl_close($ch);
        return $response;
    }

    /**
     * 校验身份证
     * 1：身份证，2：户口本
     * */
    public function checkCert($url, $type = 1)
    {
        $accessKeyId = "LTAI5tKrYVVhYu4RoMyP5Sy5";
        $accessKeySecret = "sjd2xlbWbvBUfdsFgTM5xgtFj3E9RL";
        $params = [
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"), // 动态获取当前时间戳
            "Format" => "JSON",
            "AccessKeyId" => $accessKeyId,
            "Action" => $type == 1 ? "RecognizeIdcard" : "RecognizeHousehold",
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(), // 生成唯一随机数
            "Version" => "2021-07-07",
            "Url" => $url,
            "SignatureVersion" => "1.0"
        ];

        // 计算签名
        $signature = computeSignature($params, $accessKeySecret);
        $params["Signature"] = $signature;

        // 构造最终请求URL
        $endpoint = "http://ocr-api.cn-hangzhou.aliyuncs.com/";
        $queryString = http_build_query($params);
        $requestUrl = $endpoint . "?" . $queryString;

        $res = $this->sendRequest($requestUrl);
        $data = json_decode($res, true)['Data'];
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 补贴申请页面数据回显
     * */
    public function subsidyApplyInfo()
    {
        $input = Request()->param();

        $project_id = $input['project_id'];

        if (empty($project_id)) apiReturn(2, '项目ID缺失');

        $info = Db::name('project')->field('id,name,applicable_objects,head_name,head_mobile')->where(['id' => $project_id])->find();
        if (empty($info)) apiReturn(2, '项目不存在或已删除');

        $project_file = Db::name('project_file')->where(['type' => 2])->order('type asc')->select();
        if ($project_file) {
            foreach ($project_file as &$v) {
                $v['all_name'] = $v['name'];
                $v['name'] = removeFileExtension($v['name']);
                $v['file_url'] = getHost() . getFile($v['file_id'])['path'];
            }
        }

        $subsidy_info = Db::name('subsidy')->where(['project_id' => $project_id])->find();
        $can_submit = empty($subsidy_info) || $subsidy_info['status'] == -1;
        $subsidy_file_arr = $subsidy_info['file_ids'] ? doFiles($subsidy_info['file_ids']) : [];
        $invoice_arr = $subsidy_info['invoice'] ? json_decode($subsidy_info['invoice'], true) : [];

        $data = [
            'info' => $info,
            'project_file' => $project_file,
            'can_submit' => $can_submit,
            'subsidy_file_arr' => $subsidy_file_arr,
            'invoice_arr' => $invoice_arr
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 提交申报资料
     * */
    public function submitApplySubsidy()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $project_id = $input['project_id'];
        $file_ids = $input['file_ids'];
        $invoice = $input['invoice'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        if (empty($project_id)) apiReturn(2, '项目ID缺失');
        if (empty($file_ids)) apiReturn(2, '请上传申报资料');
        if (empty(json_decode($invoice, true))) apiReturn(2, '请上传发票');

        $subsidy_count = Db::name('subsidy')->where(['project_id' => $project_id])->count();

        Db::startTrans();
        try {
            $time = time();

            $data = [
                'user_id' => $user_id,
                'project_id' => $project_id,
                'file_ids' => $file_ids,
                'invoice' => $invoice,
                'status' => 1
            ];

            if ($subsidy_count) {
                // 编辑
                $data['update_time'] = $time;

                Db::name('subsidy')->where(['project_id' => $project_id])->update($data);
            } else {
                // 新增
                $data['create_time'] = $time;

                Db::name('subsidy')->insert($data);
            }

            Db::commit();
            apiReturn(1, '提交成功');
        } catch (\Exception $e) {
            apiReturn(2, '提交失败' . $e->getMessage());
        }

    }

    /**
     * 补贴申请列表
     * */
    public function subsidyApplyList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['s.user_id'] = $user_id;
        if ($status) $where['s.status'] = $status;

        $list = Db::name('subsidy s')->join('pr_project p', 's.project_id = p.id', 'left')
            ->field('s.id,s.file_ids,p.name,p.head_name,p.head_mobile,s.create_time,s.update_time,s.status,s.refuse_reason')
            ->where($where)
            ->order('id desc')
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                switch ($v['status']) {
                    case 1:
                        $status_desc = '待审核';
                        break;
                    case 2:
                        $status_desc = '已通过';
                        break;
                    case -1:
                        $status_desc = '未通过';
                        break;
                    default:
                        $status_desc = '';
                        break;
                }
                $v['status_desc'] = $status_desc;

                $v['files_arr'] = doFiles($v['file_ids']);
                $v['create_time'] = date('Y年m月d日', $v['create_time']);
                $v['update_time'] = date('Y年m月d日', $v['update_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }


    /**
     * 我的认证
     * */
    public function userProveInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('type user_type,student_prove_id,company_prove_id')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        if ($student_prove_id = $user_info['student_prove_id']) {
            $info = Db::name('student_prove')->field('id,username,mobile,xsz_img,imgs,can_update')->where(['id' => $student_prove_id])->find();
            if (empty($info)) apiReturn(2, '认证信息不存在或已删除');
            $info['xsz_img_path'] = getPicture($info['xsz_img']);
            $info['imgs_arr'] = doImgs($info['imgs']);
        } else if ($company_prove_id = $user_info['company_prove_id']) {
            $info = Db::name('company_prove')->field('id,username,mobile,type,img,company_name,can_update')->where(['id' => $company_prove_id])->find();
            if (empty($info)) apiReturn(2, '认证信息不存在或已删除');
            switch ($info['type']) {
                case 1:
                    $type = '民企';
                    break;
                case 2:
                    $type = '机关单位';
                    break;
                case 3:
                    $type = '社会组织';
                    break;
            }
            $info['type_desc'] = $type;
            $info['img_path'] = getPicture($info['img']);
        }

        $info['user_type'] = $user_info['user_type'];

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 帮助中心
     * */
    public function articleList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('article')->field('id,title,vice_title')->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 文章详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }

    /**
     * 最新消息
     * */
    public function newMsgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0)';
        // 未读
        $sql = 'select id,title,vice_title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 消息列表
     * */
    public function msgListBak()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0)';
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /*
     * 消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if ($user_id) {
            $where['user_id'] = ['IN', [0, $user_id]];
        } else {
            $where['user_id'] = 0;
        }

        $list = Db::name('msg')->field('id,title,content,read_user,type,to_id,create_time')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $is_read = in_array($user_id, explode(',', $v['read_user']));
                if (!$is_read && $user_id) Db::name('msg')->where(['id' => $v['id']])->setField('read_user', $v['read_user'] ? $v['read_user'] . ',' . $user_id : $user_id);

                $v['is_edit'] = false;
                switch ($v['type']) {
                    case 1:
                        // 学生报名岗位审核结果通知
                        $info = Db::name('post_join')->where(['id' => $v['to_id']])->find();
                        $v['project_id'] = $info['project_id'];
                        $v['post_id'] = $info['post_id'];
                        $v['is_edit'] = $info['status'] == -1;
                        break;
                    case 2:
                        // 项目
                        $status = Db::name('project')->where(['id' => $v['to_id']])->value('status');
                        $v['is_edit'] = $status == -1;
                        break;
                    case 3:
                        // 补贴申请
                        $subsidy_info = Db::name('subsidy')->where(['id' => $v['to_id']])->find();
                        $v['is_edit'] = $subsidy_info['status'] == -1;
                        $v['project_id'] = $subsidy_info['project_id'];
                        break;
                    case 4:
                        // 企业用户审核学生报名岗位
                        $status = Db::name('post_join')->where(['id' => $v['to_id']])->value('status');
                        $v['is_edit'] = $status == -1;
                        break;

                }

                $v['content'] = doEditorContent($v['content']);
                $v['create_time_desc'] = timeAgo($v['create_time']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
        } else {
            $list = [];
        }

        $data = [
            'list' => $list,
            'count' => Db::name('msg')->where($where)->count()
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 消息详情
     * */
    public function msgDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '消息ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');

            $is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
            if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }

    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,avatar,username,student_prove_id,company_prove_id')->where(['id' => $user_id])->find();
        if ($info) {
            $info['avatar'] = doAvatar($info['avatar']);

            $info['admin_mobile'] = C('ADMIN_MOBILE');

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户不存在或已禁用');
        }
    }

    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $avatar = $input['avatar'];
        $username = $input['username'];
        $gender = $input['gender'];
        $mobile = $input['mobile'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入昵称');

        $info = Db::name('user')->where(['id' => $user_id])->find();

        if ($info) {
            $data = [
                'avatar' => $avatar,
                'username' => $username,
                'gender' => $gender,
                'mobile' => $mobile,
                'update_time' => time()
            ];

            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功');
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }

    /**
     * 意见反馈
     * */
    public function addFeedback()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $content = $input['content'];
        $imgs = $input['imgs'];
        $type = $input['type'] ? : 1;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($content)) apiReturn(2, '请输入反馈意见');

        checkContent($content);

        $data = [
            'user_id' => $user_id,
            'imgs' => $imgs,
            'content' => $content,
            'type' => $type,
            'create_time' => time()
        ];

        $res = Db::name('feedback')->insert($data);
        if ($res) {
            apiReturn(1, '反馈成功');
        } else {
            apiReturn(2, '反馈失败');
        }
    }

    /**
     * 关于我们
     * */
    public function aboutUs()
    {
        $content = Db::name('about_us')->where(['id' => 1])->value('content');

        $content = doEditorContent($content);

        apiReturn(1, '获取数据成功', $content);
    }
}
